from datetime import datetime
import json
import logging
import webapp2
from google.appengine.api import memcache
from models.Article import Article

class MeHandler(webapp2.RequestHandler):
  def get(self):
    logging.info(self.request.params)
    aboutMe = memcache.get('aboutMe')

    if aboutMe is None:
      q = Article.all()
      q.filter('subject =', 'About Me')
      q.order('-created')
      aboutMe = list(q.run())

    if 0 == len(aboutMe):
      self.response.out.write(json.dumps([]))
    else:
      memcache.set('aboutMe', aboutMe)
      self.response.out.write(json.dumps(aboutMe))

  def post(self):
    params = self.request.params

    if 'subject' not in params and 'content' not in params:
      self.request.error(404)
      return

    subject = params['subject']
    content = params['content']
    article = Article(subject = subject, content = content)
    article.put()
    aboutMe = memcache.get('aboutMe')
    if aboutMe is None: aboutMe = list(article)
    else: aboutMe = [ article ] + aboutMe
    memcache.set('aboutMe', aboutMe)